package com.lelouch.service;

import com.google.common.base.Preconditions;
import com.lelouch.bean.SysAclModule;
import com.lelouch.bean.SysDept;
import com.lelouch.common.RequestHolder;
import com.lelouch.dao.SysAclMapper;
import com.lelouch.dao.SysAclModuleMapper;
import com.lelouch.exception.ParamException;
import com.lelouch.param.AclModuleParam;
import com.lelouch.util.BeanValidator;
import com.lelouch.util.IpUtil;
import com.lelouch.util.LevelUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 部门服务
 *
 * @author lcy
 * @create 2018-06-12 15:08
 */
@Service
public class SysAclModuleService {

    @Autowired
    private SysAclModuleMapper sysAclModuleMapper;
    @Autowired
    private SysAclMapper sysAclMapper;
    @Autowired
    private SysLogService sysLogService;

    public void save(AclModuleParam aclModuleParam) {
        //检查参数是否合法
        BeanValidator.check(aclModuleParam);
        //检查部门名是否重复
        if (checkExist(aclModuleParam.getParentId(), aclModuleParam.getName(), aclModuleParam.getId())) {
            throw new ParamException("当前层级下已经有同名的权限名称，请重新命名！");
        }
        //生成level的名称
        String level = LevelUtil.calculateLevel(getLevel(aclModuleParam.getParentId()), aclModuleParam.getParentId());
        SysAclModule sysAclModule = SysAclModule.builder().name(aclModuleParam.getName()).level(level).parentId(aclModuleParam.getParentId())
                .seq(aclModuleParam.getSeq()).remark(aclModuleParam.getRemark()).status(aclModuleParam.getStatus()).build();
        sysAclModule.setOperator(RequestHolder.getUser().getUsername());
        sysAclModule.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getRequest()));
        sysAclModule.setOperateTime(new Date());
        sysAclModuleMapper.insertSelective(sysAclModule);
        sysLogService.saveAclModuleLog(null,sysAclModule);
    }

    public boolean checkExist(Integer parentId, String name, Integer id) {
        return sysAclModuleMapper.countByNameAndParentId(parentId, name, id) > 0;
    }

    public String getLevel(Integer deptId) {
        SysAclModule sysAclModule = sysAclModuleMapper.selectByPrimaryKey(deptId);
        if (sysAclModule == null) {
            return null;
        }
        return sysAclModule.getLevel();
    }

    public void update(AclModuleParam aclModuleParam) {
        //检查参数是否合法
        BeanValidator.check(aclModuleParam);
        //检查部门名是否重复
        if (checkExist(aclModuleParam.getParentId(), aclModuleParam.getName(), aclModuleParam.getId())) {
            throw new ParamException("当前层级下已经有同名的权限名称，请重新命名！");
        }
        SysAclModule before = sysAclModuleMapper.selectByPrimaryKey(aclModuleParam.getId());
        Preconditions.checkNotNull(before, "待更新的权限不存在");


        //生成level的名称
        String level = LevelUtil.calculateLevel(getLevel(aclModuleParam.getParentId()), aclModuleParam.getParentId());
        SysAclModule after = SysAclModule.builder().id(aclModuleParam.getId()).name(aclModuleParam.getName()).level(level).parentId(aclModuleParam.getParentId())
                .seq(aclModuleParam.getSeq()).remark(aclModuleParam.getRemark()).status(aclModuleParam.getStatus()).build();
        after.setOperator(RequestHolder.getUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getRequest()));
        after.setOperateTime(new Date());
        updateWithChild(before, after);
        sysLogService.saveAclModuleLog(before,after);
    }


    @Transactional
    public void updateWithChild(SysAclModule before, SysAclModule after) {
        String oldLevel = before.getLevel();
        String newLevel = after.getLevel();
        if (!StringUtils.equals(oldLevel, newLevel)) {
            List<SysAclModule> aclModuleList = sysAclModuleMapper.getChildAclModuleListByLevel(oldLevel + ".%");
            if (CollectionUtils.isNotEmpty(aclModuleList)) {
                for (SysAclModule aclModule : aclModuleList) {
                    String level = aclModule.getLevel();
                    if (level.indexOf(oldLevel) == 0) {
                        level = newLevel + level.substring(oldLevel.length());
                        aclModule.setLevel(level);
                    }
                }

                sysAclModuleMapper.batchUpdateLevel(aclModuleList);
            }
        }

        sysAclModuleMapper.updateByPrimaryKey(after);


    }

    public void delele(Integer aclModuleId) {
        SysAclModule aclModule = sysAclModuleMapper.selectByPrimaryKey(aclModuleId);
        Preconditions.checkNotNull(aclModule, "所删除的权限不存在！");
        if (sysAclModuleMapper.countByParentId(aclModuleId) > 0) {
            throw new ParamException("所删除的权限存在有子权限，不可删除！");
        }
        if (sysAclMapper.getAclCountByAclModuleId(aclModuleId) > 0) {
            throw new ParamException("所删除的权限里存在权限点，不可删除！");
        }
        sysAclModuleMapper.deleteByPrimaryKey(aclModuleId);

    }
}
